﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BigLotterySyndicate.Classes;
using SyndicateDAO.DatabaseObject;
using SyndicateBusiness.Classes;

namespace BigLotterySyndicate.Login
{
    public partial class Default : BasePublicPage
    {
        #region properties

        public string LdapError
        {
            get;
            set;
        }

        public string PrintLdapError()
        {
            return LdapError != null ? LdapError : "";
        }

        public string UserNameValue
        {
            get { return this.TextBoxUserName.Text; }
        }

        public string EmailValue
        {
            get;
            set;
        }
        public string PasswordValue
        {
            get { return this.txtbigPassword.Text; }
        }

        #endregion

        protected bool IsLogout
        {
            get
            {
                return (this.Request["Logout"] != null);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.IsLogout)
            {
                if (this.IsUserLoggedIn)
                {

                    //MCExtranet2010DB.User.LoggedInUser.CurrentBasket.DeleteUnsavedItems();
                    InsertEventLogEntry("User [" + this.LoggedInUser.id + "] logged out.",eventLog.eventType.AUDIT);

                    



                    BusinessFacade.UserBL.Logout(BusinessFacade.UserBL.LoggedInUserId.Value);
                    Session.RemoveAll();
                    Session.Clear();

                    this.GoLogoutAdmin();
                }


            }
            else if (this.IsUserLoggedIn)
            {
                if (IsAdmin)
                    this.Redirect("/Secured/");
                else
                    this.Redirect("/MyAccount/");
            }
        }

        protected void ButtonLogIn_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
                return;

            if (this.BusinessFacade.UserBL.Login(EmailValue,this.BusinessFacade.CurrentSyndicate.id))
            {
                if (Utilities.isMobileApplication())
                {
                    this.BusinessFacade.EventLogBL.InsertEntry(LoggedInUser, "User [" + LoggedInUser.id.ToString() + "] logged in on a mobile app. [" + HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"].ToString() + "]", eventLog.eventType.AUDIT);
                }
                else if (Utilities.isMobileBrowser())
                {
                    this.BusinessFacade.EventLogBL.InsertEntry(LoggedInUser, "User [" + LoggedInUser.id.ToString() + "] logged in on a mobile browser. [" + HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"].ToString() + "]", eventLog.eventType.AUDIT);
                }
                else
                {
                    this.BusinessFacade.EventLogBL.InsertEntry(LoggedInUser, "User [" + LoggedInUser.id.ToString() + "] logged in on web browser. [" + HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"].ToString() + "]", eventLog.eventType.AUDIT);
                }

                if (Page.Request.QueryString["back"] != null)
                {
                    this.Redirect(Server.UrlDecode(Page.Request.QueryString["back"].ToString()));

                }
                else
                {
                    this.Redirect("/Secured/");
                }                
            }
        }

        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = ValidateUser(EmailValue, PasswordValue);
        }

        private bool ValidateUser(string email, string password)
        {
            bool isValid = false;

            //first validate with db, if is fine then we have a domain password updated in the db

            var encodedPass = Utilities.EncodePassword(PasswordValue);

            var userEmail = UserNameValue;

            if (!userEmail.ToLower().Contains("@biggroup.co.uk"))
                userEmail += "@biggroup.co.uk";


            isValid = this.BusinessFacade.UserBL.ValidateAccountDB(userEmail, encodedPass, this.BusinessFacade.CurrentSyndicate.id, false);

            if (isValid)
            {
                EmailValue = userEmail;
                // credentials are ok, there is nothing else to do
                return true;
            }
            else
            {
                // we need to check with domain, and if is ok, update db password

                var a = new LdapAuthentication("LDAP://biggroup.lan/DC=biggroup,DC=lan");

                string e = "";

                bool auth = a.IsAuthenticated("biggroup.lan", UserNameValue, PasswordValue, out e);

                if (auth)
                {
                    // domain credentials are valid

                    EmailValue = a.GetAuthenticatedEmail();
                    isValid = this.BusinessFacade.UserBL.ValidateAccount(EmailValue, false, this.BusinessFacade.CurrentSyndicate.id);

                    //checking if user is registered in db

                    if (!isValid)
                        LdapError = "Please contact syndicate manager to get registered first.";
                    else
                    {
                        // user is registered, we need to update user password in db

                        UpdateUserPassword(EmailValue, encodedPass);

                    }
                    return isValid;
                }
                LdapError = e;
                return false;
            }
        }

        private void UpdateUserPassword(string emailValue, string encodedPass)
        {
            var user =
                this.BusinessFacade.UserBL.GetAll(this.BusinessFacade.CurrentSyndicate.id).SingleOrDefault(
                    x => x.email.ToLower() == emailValue);

            if(user != null)
            {
                user.password = encodedPass;
                this.BusinessFacade.UserBL.UpdateUser();
            }
        }
    }
}